package org.team4.dao.meta;

import java.util.HashMap;
import java.util.List;

import org.hibernate.SessionFactory;
import org.team4.constants.SQLConstant;
import org.team4.dao.GenericDAO;
import org.team4.domain.RoleModuleField;
import org.team4.domain.RoleUsers;
import org.team4.exception.CRUDException;
import org.team4.util.CacheUtil;
import org.team4.util.LoginBean;
import org.team4.util.Validate;
import org.team4.vo.RoleCache;

import org.team4.dao.meta.RoleModuleFieldDAO;


public class RoleModuleFieldDAO extends GenericDAO<RoleModuleField> {

	private static final long serialVersionUID = 1914379646816013718L;
	private static RoleModuleFieldDAO instance;
	
	public static RoleModuleFieldDAO getInstance(SessionFactory sessionFactory) {
        if(instance == null) {
            instance =  new RoleModuleFieldDAO(sessionFactory);
        }
        return instance;
    }
	
    /**
     * 构造函数
     * 
     * @param sessionFactory
     */
    private RoleModuleFieldDAO(SessionFactory sessionFactory) {
        super(sessionFactory, RoleModuleField.class);
    }
    
    /**
     * 根据用户角色用户列表查找字段的约束
     * 
     * @param ruList
     * @return
     * @throws CRUDException
     */
    public HashMap<String, String> findUsersFields(List<RoleUsers> ruList, String userId) throws CRUDException {
    	//从缓存中取出现有权限
        HashMap<String, String> fields = new HashMap<String, String>();
        RoleCache roleCache = (RoleCache) CacheUtil.get(RoleCache.CACHE_NAME, LoginBean.getLoginBean().getUser().getId());
        if(roleCache != null) {
        	fields = roleCache.getModuleFields();
        }
        if (Validate.collectionNotNull(ruList)) {
            for (RoleUsers ru : ruList) {
                List<RoleModuleField> rmfList = this.find(SQLConstant.ROLEMODULEFIELD_BY_ROLEID_HQL, ru.getRole().getId());
                if (Validate.collectionNotNull(rmfList)) {
                    for (RoleModuleField field : rmfList) {
                        fields.put(field.getWebId(), field.getRules());
                    }
                }
            }
        }
        return fields;
    }
}